package com.ggboy.item_bank.controller;

import com.ggboy.item_bank.beans.User;
import com.ggboy.item_bank.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");
        //拿到当前登录用户对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user.getRname().equals("teacher")){
            info.addStringPermission("user:teacher");
            info.addStringPermission("user:student");
        }else if (user.getRname().equals("student")){
            info.addStringPermission("user:student");
        } else if (user.getRname().equals("admin")) {
            info.addStringPermission("user:admin");
        }
        return info;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.isRegister(usernamePasswordToken.getUsername());//取出封装的数据然后进行查询
        if (user==null){
            return null;
        }
        //查到了就进行密码认证,shiro来做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }

}
